package com.bzyd.mp.datascope.strategy;

import com.bzyd.mp.datascope.DataScopeParam;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.LikeExpression;
import net.sf.jsqlparser.schema.Column;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;

public interface DataScopeStrategy {

    /**
     * 模式
     */
    String mode();

    /**
     * 构造查询条件
     */
    Expression buildWhere(Expression where, String mappedStatementId, DataScopeParam dataScopeParam);

    /**
     * 授权查看自己的
     */
    default Expression grantOwn(@NonNull Expression where, @NonNull DataScopeParam dataScopeParam, @NonNull String userName) {
        //tmp.created_by = #{}
        String equalsToLeftSql = StringUtils.isBlank(dataScopeParam.getCreatorTableAlias()) ? dataScopeParam.getCreatorColumnAlias()
                : dataScopeParam.getCreatorTableAlias() + "." + dataScopeParam.getCreatorColumnAlias();
        //第一个参数：=左边表达式
        //第二个参数：=右边表达式
//        EqualsTo equalsTo = new EqualsTo(new Column(equalsToLeftSql),new StringValue(userName));
        EqualsTo equalsTo = new EqualsTo();
        equalsTo.setLeftExpression(new Column(equalsToLeftSql));
        equalsTo.setRightExpression(new StringValue(userName));
        return new AndExpression(where, equalsTo);
    }

    /**
     * 授权查看自己所在部门及子部门的
     */
    default Expression grantOwnChildDept(@NonNull Expression where, @NonNull DataScopeParam dataScopeParam, @NonNull String deptCode) {

        //tmp.dept_code like #{}
        String likeLeftSql = StringUtils.isBlank(dataScopeParam.getDataScopeTableAlias()) ? dataScopeParam.getDataScopeColumnAlias()
                : dataScopeParam.getDataScopeTableAlias() + "." + dataScopeParam.getDataScopeColumnAlias();
        LikeExpression likeExpression = new LikeExpression();
        likeExpression.setLeftExpression(new Column(likeLeftSql));
        likeExpression.setRightExpression(new StringValue(deptCode + "%"));
        return new AndExpression(where, likeExpression);
    }
}
